#include "system_manager.h"
#include "base_log.h"
#include "base_utils.h"
#include <thread>
#include <chrono>
#include <cstdlib>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <sys/statvfs.h>
#include <sys/sysinfo.h>

namespace El {
namespace Restful {

using UpgradeManager = El::Upgrade::Upgrade;

SystemManager &SystemManager::GetInstance()
{
    static SystemManager instance;
    return instance;
}

bool SystemManager::RestartDevice(int delay, bool force)
{
    LOG_INFO("System restart requested with delay: {} seconds, force: {}", delay, force);

    // 创建一个新线程来执行重启，这样可以确保HTTP响应能够正常返回
    std::thread([delay, force] {
        if (delay > 0) {
            LOG_INFO("Waiting {} seconds before reboot", delay);
            std::this_thread::sleep_for(std::chrono::seconds(delay));
        } else {
            std::this_thread::sleep_for(std::chrono::seconds(1));
        }

        LOG_INFO("Executing reboot command now");
        std::string rebootCmd = force ? "reboot -f" : "reboot";
        if (system(rebootCmd.c_str()) != 0) {
            LOG_ERROR("Failed to execute reboot command");
            return;
        }
    }).detach();

    return true;
}

bool SystemManager::UpdateFirmware(const std::string &firmware_path)
{
    LOG_INFO("Firmware update requested: {}", firmware_path);
    // TODO: 实现固件更新的逻辑
    return true;
}

// 固件升级相关实现
bool SystemManager::InitializeUpgrade(const std::string &filename,
                                      size_t filesize,
                                      const std::string &version,
                                      const std::string &md5,
                                      int total_chunks)
{
    (void)version;
    // 验证文件名格式
    if (filename.find(".bin") == std::string::npos) {
        throw std::runtime_error("Invalid firmware file format");
    }

    // 验证文件大小
    if (filesize > 100 * 1024 * 1024) { // 100MB
        throw std::runtime_error("Firmware file too large");
    }

    // 初始化升级状态
    SetUpgradeStatus(El::Upgrade::UpgradeStatus::DOWNLOADING, "正在上传固件...");
    total_chunks_ = total_chunks;
    received_chunks_ = 0;
    file_md5_ = md5;

    // 准备升级
    return UpgradeManager::GetInstance().PrepareUpgrade();
}

bool SystemManager::HandleChunkData(const std::string &chunk_data_base64, int chunk_index, int total_chunks)
{
    (void)chunk_index;
    (void)total_chunks;
    // 解码Base64数据
    std::vector<unsigned char> chunk_data = El::Base::Base64Decode(chunk_data_base64);
    if (chunk_data.empty()) {
        throw std::runtime_error("Failed to decode chunk data");
    }

    // 追加数据到升级模块
    if (!UpgradeManager::GetInstance().Append(chunk_data.data(), chunk_data.size())) {
        throw std::runtime_error("Failed to append chunk data");
    }

    // 更新进度
    received_chunks_++;
    upgrade_progress_ = (received_chunks_ * 100) / total_chunks_;

    return true;
}

bool SystemManager::StartUpgradeProcess()
{
    SetUpgradeStatus(El::Upgrade::UpgradeStatus::VERIFYING, "正在验证固件...");

    // 设置进度回调
    UpgradeManager::GetInstance().SetProgressCallback([this](int progress, bool isSuccess) {
        upgrade_progress_ = progress;
        if (!isSuccess) {
            SetUpgradeStatus(El::Upgrade::UpgradeStatus::FAILED, "升级失败");
        } else if (progress == 100) {
            SetUpgradeStatus(El::Upgrade::UpgradeStatus::SUCCESS, "升级成功");
        }
    });

    // 开始升级
    UpgradeManager::GetInstance().StartUpgradeAsync();
    return true;
}

void SystemManager::SetUpgradeStatus(El::Upgrade::UpgradeStatus status, const std::string &message)
{
    upgrade_status_ = status;
    upgrade_message_ = message;
}

} // namespace Restful
} // namespace El